package com.skh.linkedlist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

/**
 * @Author: skh
 * @Date: 2020/3/19 10:21
 * @Description: 从尾到头打印链表
 */
public class ReversePrint {

    /**
     * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
     *
     *
     *
     * 示例 1：
     *
     * 输入：head = [1,3,2]
     * 输出：[2,3,1]
     *
     *
     * 限制：
     *
     * 0 <= 链表长度 <= 10000
     */

    public int[] reversePrint(ListNode head) {
        List<Integer> list = new ArrayList<>();

        while (head != null) {
            list.add(head.val);
            head = head.next;
        }

        Collections.reverse(list);

        int[] ints = list.stream().mapToInt(Integer::valueOf).toArray();

        return ints;
    }

    /**
     * 利用栈:先进后出
     * @param head
     * @return
     */
    public int[] reversePrint1(ListNode head) {
        Stack<Integer> stack = new Stack<>();

        while (head != null) {
            stack.push(head.val);
            head = head.next;
        }

        int[] result = new int[stack.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] =stack.pop();
        }

        return result;
    }
}
